package com.adun.scheduler.local;

import com.adun.scheduler.ISchedulerJob;
import com.adun.scheduler.SchedulerJobManager;
import com.adun.scheduler.context.SchedulerJobLocalContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.annotation.PreDestroy;
import java.util.List;

/**
 * @author ZDF
 * @date 2025/8/8
 */
@Slf4j
public class SchedulerJobLocalRegister implements SmartInitializingSingleton, DisposableBean {

    @Override
    public void afterSingletonsInstantiated() {
        initLocalHandler();
    }

    @Override
    public void destroy() {
        log.info("=============================dynamic-local-scheduler================================");
        List<ISchedulerJob> schedulerJobs = SchedulerJobManager.getSchedulerJobs();
        for (ISchedulerJob schedulerJob : schedulerJobs) {
            SchedulerJobLocalContext.destroyJob(schedulerJob.getJobName());
        }
        SchedulerJobLocalContext.clear();
        log.info("=============================dynamic-local-scheduler================================");
    }


    private void initLocalHandler() {
        log.info("=============================dynamic-local-scheduler================================");
        List<ISchedulerJob> schedulerJobs = SchedulerJobManager.getSchedulerJobs();
        for (ISchedulerJob schedulerJob : schedulerJobs) {
            SchedulerJobLocalContext.registerJob(schedulerJob.getJobName(), schedulerJob);
        }
        log.info("=============================dynamic-local-scheduler================================");
    }
}
